//
//  EFShoppingCartViewController.m
//  EnjogFood
//
//  Created by 张文瀚 on 2017/5/1.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFShoppingCartViewController.h"
#import "EFShoppingInvalidClearItem.h"
#import "EFShoppingInvalidClearCell.h"
#import "EFSepecialItem.h"
#import "EFQuickPaySelectViewController.h"
#import "EFShoppingCartCell.h"
#import "EFShoppingCartItem.h"
#import "EFSubmitOrderViewController.h"
#import "EFNewDeliveryAddressViewController.h"
#import "EFMyDeliveryAddressViewController.h"
#import "iToast.h"

@interface EFShoppingCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UIButton *allSelectBtn;
@property(nonatomic, strong)UILabel *allpriceTipLabel;
@property(nonatomic, strong)UILabel *allpriceLabel;
@property(nonatomic, strong)UIButton *payNowBtn;
@property (assign, nonatomic) NSInteger type;

@property (strong, nonatomic) UIView *rightBtnView;
@property (strong, nonatomic) UIButton *removeBtn;
@end

@implementation EFShoppingCartViewController

- (instancetype)initWithType:(NSInteger)type
{
    self = [super init];
    if (self) {
        self.type = type;
        self.title = @"购物车";
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.dataArray removeAllObjects];
        [weakSelf loadData];
        
    }];
    
    
    if (APP_CONTEXT.accountManager.accountInfo.token.length > 0) {
        //如果登录就重新拉取
        [self loadData];
    }else{ //如果没有登录 就用本地的
        NSMutableArray *pItems = nil;
        if (self.type == 1) {
            pItems = APP_CONTEXT.shoppingCartManager.scanProductsCart;
            [self updateAllPrice:APP_CONTEXT.shoppingCartManager.scanTotalPrice];
            
        }else{
            pItems = APP_CONTEXT.shoppingCartManager.storeProductsCart;
            [self updateAllPrice:APP_CONTEXT.shoppingCartManager.storeTotalPrice];
        }
        for (EFSepecialItem *pI in pItems) {
            EFShoppingCartItem *sI = [EFShoppingCartItem castFromProductItem:pI];
            sI.type = [NSNumber numberWithInteger:self.type];
            [self.dataArray addObject:sI];
        }
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData{
    [self showHUD];
    self.bottomView.hidden = YES; 
    __weak typeof(self) weakSelf = self;
    [APP_CONTEXT.net getCartListWithIsLocalDelivery:APP_CONTEXT.isLocalDelivery whCode:APP_CONTEXT.whCode type:self.type OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.HUD hide:YES];
        if (code == 0) {
            NSArray *list = [info valueForKey:@"list"];
            NSArray *naList = [info valueForKey:@"naList"];
            
            if(self.type == 0){
                [APP_CONTEXT.shoppingCartManager.storeProductsCart removeAllObjects];
            }else if(self.type == 1){
                [APP_CONTEXT.shoppingCartManager.scanProductsCart removeAllObjects];
            }
            
            if (list.count == 0 && naList.count == 0) {
                [weakSelf showEmptyImageView:@"bg_icon_cart" message:@"您的购物车还未添加任何商品"];
            }else{
                weakSelf.bottomView.hidden = NO;
                for (NSDictionary *dic in list) {
                    EFShoppingCartItem *item = [EFShoppingCartItem yy_modelWithDictionary:dic];
                    item.type = [NSNumber numberWithInteger:self.type];
                    [weakSelf.dataArray addObject:item];
                    
                    if(self.type == 0){
                        [APP_CONTEXT.shoppingCartManager addToStoreProduct:[item castToSpecialItem ]];
                    }else if(self.type == 1){
                        [APP_CONTEXT.shoppingCartManager addToScanProduct:[item castToSpecialItem]];
                    }
                }
                
                for (int i= 0; i < naList.count; i++) {
                    NSDictionary *dic = naList[i];
                    EFShoppingCartItem *item = [EFShoppingCartItem yy_modelWithDictionary:dic];
                    item.type = [NSNumber numberWithInteger:self.type];
                    item.invalid = YES;
                    if (i==0) {
                        item.invalidFirst = YES;
                    }
                    [weakSelf.dataArray addObject:item];
                }
                
                if (naList.count > 0) {
                    EFShoppingInvalidClearItem *item = [[EFShoppingInvalidClearItem alloc] init];
                    [weakSelf.dataArray addObject:item];
                }
                [weakSelf modifyAllData:true];
            }
        }
    }];
}

- (void)initView{
    //右按钮
    [self.rightBtnView addSubview:self.removeBtn];
    self.removeBtn.left =self.rightBtnView.width - self.removeBtn.width - 20;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtnView];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
    
    [self.view addSubview:self.tableView];
    
    self.bottomView.bottom = kScreenHeight - kStatusBarHeight;
    [self.view addSubview:self.bottomView];
    
    self.allSelectBtn.centerY = self.bottomView.height/2.f;
    self.allSelectBtn.left = scale(18.f);
    [self.bottomView addSubview:self.allSelectBtn];
    
    self.allpriceTipLabel.left = self.bottomView.width/3;
    self.allpriceTipLabel.centerY = self.allSelectBtn.centerY;
    [self.bottomView addSubview:self.allpriceTipLabel];
    
    self.allpriceLabel.text = @"￥0.00";
    [self.allpriceLabel sizeToFit];
    self.allpriceLabel.left = self.allpriceTipLabel.right + 5.f;
    self.allpriceLabel.centerY = self.allSelectBtn.centerY;
    [self.bottomView addSubview:self.allpriceLabel];
    
    self.payNowBtn.right = self.bottomView.width;
    [self.bottomView addSubview:self.payNowBtn];
}

- (void)updateAllPrice:(CGFloat)price{
    self.allpriceLabel.text = [NSString stringWithFormat:@"%.2f",price];
    [self.allpriceLabel sizeToFit];
    self.allpriceLabel.left = self.allpriceTipLabel.right + 5.f;
    self.allpriceLabel.centerY = self.allSelectBtn.centerY;
}

-(void)removeGood:(NSString*) productId {
    __weak typeof(self) weakSelf = self;
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消" action:^{
        //[weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"确认" action:^{
        [APP_CONTEXT.net subCart:productId qty:[NSNumber numberWithFloat:0] type:[NSNumber numberWithInteger:self.type] barcode:@"" OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
             if(code == 0){
                 [self removeData:productId];
             }
        }];
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确定要将商品从购物车中移除吗？" message:nil cancelButtonItem:cancel otherButtonItems:ok,nil];
    [alertView show];
}

-(void)onClickRemove{
    __weak typeof(self) weakSelf = self;
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消" action:^{
        //[weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"确认" action:^{
       [APP_CONTEXT.net emptyCart: [NSNumber numberWithInteger:self.type] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(code == 0){
                weakSelf.bottomView.hidden = YES;
                [weakSelf showEmptyImageView:@"bg_icon_cart" message:@"您的购物车还未添加任何商品"];
                [weakSelf.dataArray removeAllObjects];
                [weakSelf.tableView reloadData];
                weakSelf.allSelectBtn.selected = false;
                [weakSelf updateAllPrice:0.0f];
                
                [APP_CONTEXT.shoppingCartManager.storeProductsCart removeAllObjects];
                [APP_CONTEXT.shoppingCartManager.scanProductsCart removeAllObjects];
                
            }else{
                [[iToast makeText:message]show];
            }
       }];
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确认清空购物车中商品？" message:nil cancelButtonItem:cancel otherButtonItems:ok,nil];
    [alertView show];
}

-(void)removeInvalidGoods{
    __weak typeof(self) weakSelf = self;
    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消" action:^{
       // [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    RIButtonItem *ok = [RIButtonItem itemWithLabel:@"确认" action:^{
        NSMutableString* productIds = [[NSMutableString alloc]init];
        for(int i = 0 ; i < weakSelf.dataArray.count; ++i){
            ICTableViewItem* item = [self.dataArray objectAtIndex:i];
            if([item isKindOfClass:[EFShoppingCartItem class]]){
                EFShoppingCartItem* shopCartItem = (EFShoppingCartItem*)item;
                if(shopCartItem.invalid){
                    if(productIds.length == 0){
                        NSString* tempItem = [NSString stringWithFormat:@"%@",shopCartItem.id];
                        [productIds appendString:tempItem];
                    }else{
                        NSString* tempItem = [NSString stringWithFormat:@",%@",shopCartItem.id];
                        [productIds appendString:tempItem];
                    }
                }
            }
        }
        
        [APP_CONTEXT.net removeInvalidGood:[NSNumber numberWithInteger:self.type] productIds:productIds OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
            if(code == 0){
                NSMutableIndexSet* indexSet = [[NSMutableIndexSet alloc]init];
                for(int i = 0 ; i < weakSelf.dataArray.count; ++i){
                    ICTableViewItem* item = [self.dataArray objectAtIndex:i];
                    if([item isKindOfClass:[EFShoppingCartItem class]]){
                        EFShoppingCartItem* shopCartItem = (EFShoppingCartItem*)item;
                        if(shopCartItem.invalid){
                            [indexSet addIndex:i];
                        }
                    }else if([item isKindOfClass:[EFShoppingInvalidClearItem class]]){
                        [indexSet addIndex:i];
                    }
                }
                [weakSelf.dataArray removeObjectsAtIndexes:indexSet];
                [weakSelf.tableView reloadData];
                if(weakSelf.dataArray.count == 0 ){
                    [weakSelf showEmptyImageView:@"bg_icon_cart" message:@"您的购物车还未添加任何商品"];
                }
                
            }else{
                [[iToast makeText:message]show];
            }
        }];
    }];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确认清空暂无法购买商品？" message:nil cancelButtonItem:cancel otherButtonItems:ok,nil];
    [alertView show];
}

- (void)onClickAllSelectBtn{
    self.allSelectBtn.selected = !self.allSelectBtn.selected;
    [self modifyAllData:self.allSelectBtn.selected];
}

- (void)onClickPayNowBtn{
    //选中的全部商品
    NSMutableArray* selectArray = [NSMutableArray array];
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFShoppingCartItem class]]){
            if(((EFShoppingCartItem*)object).selected ){
            [selectArray addObject:(EFShoppingCartItem*)object];
           }
        }
    }
    
    if(selectArray.count <= 0){
        [[iToast makeText:@"请选择要购买的物品"]show];
        return;
    }
    
    
    EFMyDeliveryAddressViewItem* defaultAddres  = APP_CONTEXT.addressManager.defaultAddress;
    if(defaultAddres == nil ||  !defaultAddres.id){
        if(APP_CONTEXT.addressManager.addressArray != nil  && [APP_CONTEXT.addressManager.addressArray count] > 0){
            EFMyDeliveryAddressViewController *address = [[EFMyDeliveryAddressViewController alloc] init];
            [ICNavigator pushViewController:address animated:YES];
        }else{
            EFNewDeliveryAddressViewController *shopSubmitOrder = [[EFNewDeliveryAddressViewController alloc] initWithLocation];
            [ICNavigator pushViewController:shopSubmitOrder animated:YES];
        }
        return;
    }
    
    if(self.type == 0){
        EFSubmitOrderViewController *shopSubmitOrder = [[EFSubmitOrderViewController alloc] initWithData:selectArray];
        [ICNavigator pushViewController:shopSubmitOrder animated:YES];
    }else {
        EFQuickPaySelectViewController *selectVC = [[EFQuickPaySelectViewController alloc] initWithShopData:selectArray];
        [ICNavigator pushViewController:selectVC animated:YES];
    }
}

#pragma mark - TableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICTableViewItem *item = self.dataArray[indexPath.row];
    NSString *identifier = NSStringFromClass(item.viewClass);
    ICTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil){
        cell = [[item.viewClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if ([item isKindOfClass:[ICTableViewItem class]]) {
        [cell setObject:item];
    }
    
    if(([item isKindOfClass:[EFShoppingCartItem class]])){
        ((EFShoppingCartCell *)cell).selectBlock = ^(Boolean select){
            ((EFShoppingCartItem*)item).selected = select;
            
            [self modifyData];
        };
        
        ((EFShoppingCartCell *)cell).changeBlock = ^(NSInteger count){
            ((EFShoppingCartItem*)item).qty = [NSNumber numberWithInteger:count];
            if(count == 0){
                [self removeGood:((EFShoppingCartItem*)item).id];
            }
            
            [self modifyData];
            
        };
        
    }
    
    if(([item isKindOfClass:[EFShoppingInvalidClearItem class]])){
        ((EFShoppingInvalidClearCell *)cell).clearblock = ^(){
            [self removeInvalidGoods];
        };
    }
    
    return cell;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            ICTableViewItem* item = self.dataArray[indexPath.row];
            if(([item isKindOfClass:[EFShoppingCartItem class]])){
                EFShoppingCartItem* shopItem = (EFShoppingCartItem*)item;
                [APP_CONTEXT.net subCart:shopItem.id qty:shopItem.qty type:[NSNumber numberWithInteger:self.type] barcode:@"" OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
                    if(code == 0){
                        [self removeData:shopItem.id];
                    }
                }];
            }
        }
    }
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}


- (UIView *)rightBtnView{
    if (!_rightBtnView) {
        _rightBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 22)];
        _rightBtnView.backgroundColor = [UIColor whiteColor];
    }
    return _rightBtnView;
}

- (UIButton *)removeBtn{
    if (!_removeBtn) {
        _removeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        [_removeBtn setImage:IMG(@"nav_delete_icon_default") forState:UIControlStateNormal];
        [_removeBtn setImage:IMG(@"nav_delete_icon_default") forState:UIControlStateSelected];
        [_removeBtn addTarget:self action:@selector(onClickRemove) forControlEvents:UIControlEventTouchUpInside];
    }
    return _removeBtn;
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight - 50.f)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50.f)];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

- (UIButton *)allSelectBtn{
    if (!_allSelectBtn) {
        _allSelectBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50.f, 22.f)];
        [_allSelectBtn setImage:IMG(@"cartlist_Unselected_icon") forState:UIControlStateNormal];
        [_allSelectBtn setImage:IMG(@"cartlist_selected_icon") forState:UIControlStateSelected];
        [_allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];
        [_allSelectBtn setTitleColor:kBlack333 forState:UIControlStateNormal];
        [_allSelectBtn addTarget:self action:@selector(onClickAllSelectBtn) forControlEvents:UIControlEventTouchUpInside];
        _allSelectBtn.titleLabel.textColor = kBlack333;
        _allSelectBtn.titleLabel.font = [UIFont systemFontOfSize:13.f];
    }
    return _allSelectBtn;
}


- (UIButton *)payNowBtn{
    if (!_payNowBtn) {
        _payNowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth/3.f, 50.f) NormalTitile:@"立即结算" Type:ZYJGreenButtonType];
        [_payNowBtn addTarget:self action:@selector(onClickPayNowBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _payNowBtn;
}

- (UILabel *)allpriceLabel{
    if (!_allpriceLabel) {
        _allpriceLabel = [[UILabel alloc] init];
        _allpriceLabel.backgroundColor = [UIColor clearColor];
        _allpriceLabel.textColor = RGBCOLOR(0x69BA45);
        _allpriceLabel.font = [UIFont systemFontOfSize:15.f];
    }
    return _allpriceLabel;
}


- (UILabel *)allpriceTipLabel{
    if (!_allpriceTipLabel) {
        _allpriceTipLabel = [[UILabel alloc] init];
        _allpriceTipLabel.backgroundColor = [UIColor clearColor];
        _allpriceTipLabel.textColor = kBlack333;
        _allpriceTipLabel.font = [UIFont systemFontOfSize:13.f];
        _allpriceTipLabel.text = @"总价";
        [_allpriceTipLabel sizeToFit];
    }
    return _allpriceTipLabel;
}


-(void)modifyData{
    float totalPrice = 0 ;
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFShoppingCartItem class]]){
            if(((EFShoppingCartItem*)object).selected ){
                totalPrice += ((EFShoppingCartItem*)object).qty.floatValue*((EFShoppingCartItem*)object).salePrice.floatValue;
            }
        }
    }
    [self.allpriceLabel setText:@(totalPrice).stringValue];
    [self.allpriceLabel sizeToFit];
}


-(void)modifyAllData:(Boolean)select{
    float totalPrice = 0 ;
    for (NSObject *object in self.dataArray) {
        if([object isKindOfClass:[EFShoppingCartItem class]]  && !((EFShoppingCartItem*)object).invalid){
            ((EFShoppingCartItem*)object).selected = select;
            if(select){
                totalPrice += ((EFShoppingCartItem*)object).qty.floatValue*((EFShoppingCartItem*)object).salePrice.floatValue;
            }
        }
    }
    [self.allpriceLabel setText:@(totalPrice).stringValue];
    [self.allpriceLabel sizeToFit];
    [self.tableView reloadData];
}

-(void)removeData:(NSString*)productId{
    int index = -1;
    for (int i = 0 ; i < self.dataArray.count; ++i){
        NSObject *object = [self.dataArray objectAtIndex:i];
        if([object isKindOfClass:[EFShoppingCartItem class]]  && !((EFShoppingCartItem*)object).invalid){
            if([((EFShoppingCartItem*)object).id isEqual:productId]){
                index = i;
                break;
            }
        }
    }
    if(index != -1){
        [self.dataArray removeObjectAtIndex:index];
        [APP_CONTEXT.shoppingCartManager removeObject:productId type:self.type];
        [self.tableView reloadData];
        [self modifyData];
        if(self.dataArray.count == 0 ){
            [self showEmptyImageView:@"bg_icon_cart" message:@"您的购物车还未添加任何商品"];
        }  
    }
    
    //        [APP_CONTEXT.net emptyCart: [NSNumber numberWithInteger:self.type] OnComplete:^(NSInteger code, NSDictionary *info, NSString *message) {
    //            if(code == 0){
    //                weakSelf.bottomView.hidden = YES;
    //                [weakSelf showEmptyImageView:@"bg_icon_cart" message:@"您的购物车还未添加任何商品"];
    //                [weakSelf.dataArray removeAllObjects];
    //                [weakSelf.tableView reloadData];
    //                weakSelf.allSelectBtn.selected = false;
    //                [weakSelf updateAllPrice:0.0f];
    //
    //                [APP_CONTEXT.shoppingCartManager.storeProductsCart removeAllObjects];
    //
    //            }else{
    //               
    //            }
    //        }];
}


@end
